from time  import sleep
# 别名
from time  import sleep as newSleep
newSleep(5)
# w写入模式路径不存在会创建文件
with open('00text.txt', "w", encoding="UTF-8") as f1:
    # write只是写入了内存在还没写入硬盘,通过flush可以将内存中积攒的内容写入硬盘
    # 如果文件存在会清空重新写入内容
    f1.write('hello world======123')
    # f1.flush()
    # time.sleep(10)
# a表示追加
with open('00text.txt', "a", encoding="UTF-8") as f1:
    # write只是写入了内存在还没写入硬盘,通过flush可以将内存中积攒的内容写入硬盘
    # 如果文件存在会清空重新写入内容
    f1.write('\naaaaahello world======123')
    # f1.flush()
    # time.sleep(10)

with open('00BaseFile.txt', "r", encoding="UTF-8") as f3:
    for line in f3.readlines():
        if not line.strip():
            continue
        appendLine = line.replace('甲醛', '')
        with open('00BaseFileDB.txt', "a", encoding="UTF-8") as f4:
            f4.write(f'\n{appendLine}')

# try,except捕获异常
try:
    with open('00text1.txt', "r", encoding="UTF-8") as f5:
        print(f5)
except:
    # 文件不存在就改为W模式创建文件
    # with open('00text1.txt',"w",encoding="UTF-8") as f5:
    #     print(f5)
    print('出错啦!!!')

# 捕获特定的异常
try:
    print(name)
except NameError as e:
    print(e)

#捕获多个异常
try:
    1/0
    print(name)
except (NameError,ZeroDivisionError) as e:
    # 捕获变量未定义或者0做为被除数的异常
    print(e)

#捕获全部的异常
try:
    1/0
    print(name)
except Exception as e:
    # 捕获全部的异常Exception对象
    print(e)
else:
    # else没有异常的情况
    print('恭喜没有异常')
finally:
    # finally无论是否有异常都会执行
    print("无论是否有异常都会执行")


#异常的传递性
def fun1():
    print("fun1开始执行")
    1/0
    print("fun1结束执行")

def fun():
    print("fun2开始执行")
    fun1()
    print("fun2结束执行")

def main():
    try:
        print("mian开始执行")
        fun()
    except Exception as e:
        print(e)
    finally:
        print("mian结束执行")

main()




